import React from 'react';
import { connect } from 'react-redux';
import baseService from 'share/base.service';

class ExpenseTypeRenderer extends React.Component {

  componentDidMount() {
    const { expenseCache, id } = this.props;
    if (!expenseCache[id]) {
      this.fetch(id);
    }
  }

  componentDidUpdate(prevProps) {
    if (prevProps.id !== this.props.id) {
      this.fetch(this.props.id);
    }
  }

  /**
   * @param {string} id
   */
  fetch = async (id) => {
    this.props.dispatch({
      type: 'SET_EXPENSE_CACHE',
      payload: {
        expenseTypeOID: id,
        _status: 'pending'
      }
    });

    try {
      const res = await baseService.getExpenseTypeByOID(id);
      if (res.status >= 400) {
        throw new Error(res.response.message);
      }
      this.props.dispatch({
        type: 'SET_EXPENSE_CACHE',
        payload: {
          ...res.data
        }
      });
    } catch (e) {
      console.error(e.message);
    }
  }

  render() {
    const { expenseCache, id } = this.props;
    const hitCache = expenseCache[id] || {expenseTypeOID: id, _status: 'pending'};
    if (this.props.render) {
      return this.props.render(hitCache);
    }
    return (
      <div>{hitCache.name || id}</div>
    );
  }
}


function mapStateToProps(state) {
  return {
    expenseCache: state.expenseCache,
  };
}


export default connect(mapStateToProps)(ExpenseTypeRenderer);
